package com.example.picturebacked.api.imagesearch.sub;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Autheor LBT
 * 以图搜图方法（step 1）
 * 根据图片url获取到返回的api
 */
@Slf4j
public class GetImagePageUrlApi {
    /**
     * 获取页面图片地址
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数，因为请求数据需要使用表单提交
        /**
         * image  https%3A%2F%2Fimages.unsplash.com%2Fphoto-1506744038136-46273834b3fb%3Fixlib%3Drb-4.0.3%26ixid%3DM3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%253D%253D%26auto%3Dformat%26fit%3Dcrop%26w%3D1280%26q%3D80
         * tn pc
         * from pc
         * image_source PC_UPLOAD_URL
         * sdkParams {"data":"49c8e8cdd21f33266e03e0de7004fd94bbff7fd708a0ff0bb4bec8b5174882f2728fe86082b3e13b884a066a89f09fc702f3663c8171fae3ed703ea7a2465762f6eea2114671d4a4f9dd211ae6e2663e","key_id":"23","sign":"813536cf"}
         */
        Map<String, Object> formDate = new HashMap<>();
        formDate.put("image", imageUrl);
        formDate.put("tn", "pc");
        formDate.put("from", "pc");
        formDate.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;
        String acsToken = "1756873166158_1756900421883_vFMjILFvEd8TeDq6WNDwGwFuQIJdl911T+a93pwIvW5txSVjlgayJSjB7lhTx3LEHX/PZ0foxkcD1xGED/eA7t9FNV0DYcbDQjCCw/driSsuKR8G+W2j8qnfPtfKdxQX4iVDVB9kPKN1eAiThFl9P24cbiNgisIbRqB++1UffKjNpgoTVObZuMirjBgS/tntkD/XjHrATBIHp579z3O23mHfst+6ktCa2qTHQYV97FWiro4iKp1KL2EWgWvizQGZabPsicd5S2gvGq8Q8HVHETvw+TzimMcsBciTVm1GUkx6y4Co9FDKuhswoAdt/+SqdMZkHy9K2nkgg4pMCKlogL9IYO3Gh4r8RvNkxWudD2Ob8Zhn82+j66BDFJ3MXgqNLiUUnlJnpFyHEwOA5eOEhEBay9SNdwhPhn0BK1Xv9/hfqwS06f8yGXQmh631DgEJo3/r5oqmUwv/veDec4LB/0BtRS1uQcPsvknNOBn40gTAGCCvW+2IPhnkUv1mVo4W";
        try {
            // 向百度以图搜图地址发送请求，提交上传的地址并接受返回结果
            HttpResponse response = HttpRequest.post(url)
                    .form(formDate)
                    .header("Acs-Token", acsToken)
                    .timeout(100000)
                    .execute();
            // 判断相应状态
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败1");
            }
            // body中的内容json字符串，body中date也是json字符串
            // 获取body中的内容，并将其转换成Map
            String body = response.body();
            Map<String, Object> result = JSONUtil.toBean(body, Map.class);
            // 处理body的响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败2");
            }
            // 获取date中的数据
            Map<String, Object> date = (Map<String, Object>) result.get("data");
            String rawUrl = (String) date.get("url");
            // 因为获取的数据中有转义字符，使用hutool的URL工具类取消掉转义字符
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            // 如果URL为空
            if (searchResultUrl == null) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未有返回结果");
            }
            return searchResultUrl;
        } catch (Exception e) {
            log.error("搜索结果失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索结果失败");
        }
    }

    /**
     * 测试以图搜图功能
     */
    public static void main(String[] args) {
        String url = "https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1280&q=80";
        String imagePageUrl = getImagePageUrl(url);
        System.out.println(imagePageUrl);
    }
}























